package org.skywork.top.core.algorithm.num;

import java.util.Arrays;


/**
 * 两数之和
 */
public class no_1 {

    public static int[] twoSum(int[] nums, int target) {
        int[] result = new int[2];
        for(int i = 0; i < nums.length - 1; i++){
            int temp = target - nums[i];
            int index = binarySearch(nums, i + 1, nums.length, temp);
            if(index > 0 && index != i){
                result[0] = i;
                result[1] = index;
                break;
            }
        }
        return result;
    }

    private static int binarySearch(int[] a, int fromIndex, int toIndex,
                                     int key) {
        int low = fromIndex;
        int high = toIndex - 1;

        while (low <= high) {
            int mid = (low + high) >>> 1;
            int midVal = a[mid];

            if (midVal < key)
                low = mid + 1;
            else if (midVal > key)
                high = mid - 1;
            else
                return mid; // key found
        }
        return -(low + 1);  // key not found.
    }

    public static void main(String[] args) {
        int[] nums = {3,2,4};
        int target = 6;
        int[] twoSum = twoSum(nums, target);
        System.out.println(Arrays.toString(twoSum));
    }
}
